import {plays, invoices} from "./data.js";
import {createStatement} from "./createStatementDataOriginal.js";


// 和第二版对比
// 拆分阶段

// 将所有代码抽取到一个新的函数中，并重命名为renderPlainText，表示当前函数输出简单文本格式的账单
// 创建一个中转数据对象
// 将customer, performance对象放入中转对象中
// 将plays对象一一挂载到performance对象上
// 计算performance对应的amount和credits
// 将for循环改为reduce

// 重构后的版本-V1.3 增加返回Html格式账单
function statement(invoice, plays) {
  // return renderPlainText(createStatement(invoice, plays));
  document.body.innerHTML = renderHtml(createStatement(invoice, plays))
}

// 将账单数据以普通文本展示
function renderPlainText(statementData) {
  let result = statementData.invoice.performances
    .reduce((prev, curr) => prev += `${curr.play.name}: ${statementData.usd(statementData.amountFor(curr))} (${curr.audience} seats)\n`,
      `Statement for ${statementData.invoice.customer}\n`);

  result += `Amount owed is ${statementData.usd(statementData.totalAmount(statementData.invoice))}\n`;
  result += `You earned ${statementData.totalVolumeCredits(statementData.invoice)} credits \n`;

  return result;

}

for (let invoice of invoices) {
  let result = statement(invoice, plays);
  console.log(result);
}

function renderHtml(statementData) {

  let htmlContent = "<table><tr><th>play</th><th>seats</th><th>cost</th></tr>";

  // 拼接html
  return statementData.invoice.performances
    .reduce((prev, curr) => prev += `<tr><td>${curr.play.name}</td>
<td>${curr.audience}</td>
<td>${statementData.usd(statementData.amountFor(curr))}</td>
</tr>`, htmlContent) + "</table>"

}